/*
 * LoadShader.cpp
 *
 *  Created on: 15 Nov 2013
 *      Author: axel
 */

#include <GL/glew.h>
#include "LoadShader.h"

#include <stdlib.h>
#include <iostream>


LoadShader::LoadShader(void)
{
}


LoadShader::~LoadShader(void)
{
}

void LoadShader::addShader(GLuint ShaderProgram, const char* pShaderText, GLenum ShaderType) {
    GLuint ShaderObj = glCreateShader(ShaderType);

    if (ShaderObj == 0) {
        std::cout << "Error creating shader type " << ShaderType;
        exit(1);
    }

    const GLchar* p[1];
    p[0] = pShaderText;
    GLint Lengths[1];
    Lengths[0]= strlen(pShaderText);
    glShaderSource(ShaderObj, 1, p, Lengths);
    glCompileShader(ShaderObj);
    GLint success;
    glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &success);
    if (!success) {
        GLchar InfoLog[1024];
        glGetShaderInfoLog(ShaderObj, 1024, NULL, InfoLog);
        std::cout <<  "Error compiling shader type " << ShaderType;
        exit(1);
    }
    glAttachShader(ShaderProgram, ShaderObj);
    glDeleteShader(ShaderObj);
}

void LoadShader::compileShaders(const char* pVS, const char* pFS, GLuint &ShaderProgram) {
    if (ShaderProgram == 0) {
    	std::cout <<  "Error creating shader program\n";
        exit(1);
    }

    addShader(ShaderProgram, pVS, GL_VERTEX_SHADER);
    addShader(ShaderProgram, pFS, GL_FRAGMENT_SHADER);

    GLint Success = 0;
    GLchar ErrorLog[1024] = { 0 };

    glLinkProgram(ShaderProgram);
    glGetProgramiv(ShaderProgram, GL_LINK_STATUS, &Success);
	if (Success == 0) {
		glGetProgramInfoLog(ShaderProgram, sizeof(ErrorLog), NULL, ErrorLog);
		std::cout <<  "Error linking shader program: \n" << ErrorLog;
        exit(1);
	}

    glValidateProgram(ShaderProgram);
    glGetProgramiv(ShaderProgram, GL_VALIDATE_STATUS, &Success);
    if (!Success) {
        glGetProgramInfoLog(ShaderProgram, sizeof(ErrorLog), NULL, ErrorLog);
        std::cout <<  "Invalid shader program: \n" << ErrorLog;
        exit(1);
    }
}
